package com.dgut.cbd.util;

import com.dgut.cbd.config.ScheduleConfig;
import com.dgut.cbd.entity.DataModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Program: exp3
 * @Description:
 * @Author: cbd
 * @Create: 2021-05-10
 * @Version: 1.0.0
 **/
@Component
@Slf4j(topic = "myLog")
public class DataProcHelper {


    static public CSVParser wgetAndIterate(String url, RestTemplate restTemplate) throws Exception {
        URI uri = UriComponentsBuilder.fromUriString(url).build(42);
        RequestEntity<Void> requestEntity = RequestEntity
                .get(uri)
                .header("User-Agent", "Mozilla/5.0")
                .build();
        ResponseEntity<Resource> response = restTemplate.exchange(requestEntity, Resource.class);
        Resource body = response.getBody();
        Reader in = new InputStreamReader(body.getInputStream());
//        ClassPathResource classPathResource = new ClassPathResource("time_series_covid19_confirmed_global.csv");
//        Reader in = new FileReader(classPathResource.getFile());
        return CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);
    }

    static public Map<String, List<DataModel>> packageDate(CSVParser rawData) {
        Map<String, List<DataModel>> res = new HashMap<>();
        boolean headFlag = true; // 标记未访问表头
        List<String> headerNames = rawData.getHeaderNames(); // 表头

        for (CSVRecord item : rawData) {

//            省的名字小写
            DataModel dataModel = new DataModel().setState(item.get("Province/State").toLowerCase())
                    .setCountry(item.get("Country/Region"))
                    .setLatestTotalCase(Integer.valueOf(item.get(item.size() - 1)))
                    .setDiffFromPreDay(Integer.valueOf(item.get(item.size() - 1))
                            - Integer.valueOf(item.get(item.size() - 2)));

            dataModel.setDate(headerNames.subList(4, item.size()));
//            整理下日期格式
            dataModel.setDate(
                    dataModel.getDate().stream().map(str -> {
                    String[] split = str.split("/");
                    return split[0] + "/" + split[1] + "/" + "20" + split[2];
            }).collect(Collectors.toList()));

//            遍历日期数据，然后填入dataModel中，数据包括当天的总数和当天的人数
            for (int i = 4, lastDayTotal = 0; i < item.size(); i++) {
//                当天的人数，分支的作用是处理第一天
                if (i != 4) {
                    dataModel.getNums().add(Integer.valueOf(item.get(i)) - lastDayTotal);
//                    dataModel.getDateNumMap().put(headerNames.get(i),
//                            Integer.valueOf(item.get(i)) - lastDayTotal);
                }else{
                    dataModel.getNums().add(0);
                }

//                当天的总人数
                lastDayTotal = Integer.valueOf(item.get(i));
                dataModel.getTotal().add(lastDayTotal);
//                dataModel.getDateTotalMap().put(headerNames.get(i), lastDayTotal);
            }

//            国家的名字都用小写，方便搜索
            List<DataModel> countryDatas = res.get(dataModel.getCountry().toLowerCase());
            if (countryDatas == null) {
                countryDatas = new LinkedList<>();
                res.put(dataModel.getCountry().toLowerCase(), countryDatas);
            }
            countryDatas.add(dataModel);
        }

        return res;
    }
}
